﻿using System;
using System.Collections.Generic;
using ExcelDna.Integration;

namespace Cubicle.Excel.Shared
{
    public class ClientManager<T>
    {
        public readonly Dictionary<string, T> Clients =
            new Dictionary<string, T>();

        public T DefaultClient { get; protected set; }

        public bool MakeDefault(string name)
        {
            if (!Has(name)) return false;

            DefaultClient = Clients[name];
            return true;
        }

        public bool Remove(string name)
        {
            if (!Clients.ContainsKey(name)) return false;
            var client = Get(name);
            if (client is IDisposable)
                ((IDisposable)client).Dispose();
            Clients.Remove(name);
            return true;
        }

        public void Add(string alias, T client)
        {
            Clients[alias] = client;

            if (Clients.Count == 1)
                DefaultClient = client;
        }

        public T Get(string name)
        {
            if (String.IsNullOrEmpty(name) || name.GetType() == typeof(ExcelMissing)) 
                return DefaultClient;
            T client;
            Clients.TryGetValue(name, out client);
            return client;
        }

        public bool Has(string name)
        {
            // Check if this name exists
            return Clients.ContainsKey(name);
        }

    }
}